/*
 * Instruction.java
 *
 * Created on March 19, 2007, 6:34 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package moto9s12sim;

/**
 *
 * @author Fergus Earnshaw
 */
public class Instruction {
    
    /** Creates a new instance of Instruction */
    String strAssemblyCode;
    byte[] bCodes;
    short shAddr;
    
    public Instruction()
    {
        this.strAssemblyCode = "Invalid Instruction";        
    }
    
    public boolean excute(M9S12 CPU)
    {
        this.shAddr = (short)CPU.PC.getUnsignedRegister();
        this.bCodes = new byte[1];
        this.bCodes[0] = CPU.bMemory[this.shAddr];
        CPU.PC.inc();
        
        printInstruction(CPU);
        //I think the first invalid instruction should halt excution
        return false;
    }
    
    protected void printInstruction(M9S12 CPU)
    {
        String strCodes;
        
        strCodes = "";
        
        for (int i = 0; i < this.bCodes.length; i++)
        {
            strCodes += printByte(this.bCodes[i]);
        }
        
        CPU.writelnToConsole(printAddr() + "\t" + strCodes + "\t\t\t" + this.strAssemblyCode);
    }
    
    protected String printAddr()
    {
        String strTmp;
        
        strTmp = Integer.toHexString((this.shAddr >= 0) ? (int)this.shAddr : 65536 + (int)this.shAddr).toUpperCase();
        
        while(strTmp.length() < 4)
        {
            strTmp = "0" + strTmp;
        }
        
        return strTmp;
    }
    
    protected String printByte(byte bTmp)
    {
        String strTmp;
        strTmp = Integer.toHexString((bTmp >= 0) ? bTmp : 256 + bTmp).toUpperCase();
        
        if(strTmp.length() < 2)
        {
            strTmp = "0" + strTmp;
        }
        
        return strTmp;
    }
        
}